package com.ttx.pattern.example.chain.tomcat.filterchain.filter;

import com.ttx.pattern.example.chain.tomcat.filterchain.Filter;
import com.ttx.pattern.example.chain.tomcat.filterchain.FilterChain;
import com.ttx.pattern.example.chain.tomcat.filterchain.FilterConfig;
import com.ttx.pattern.example.chain.tomcat.servlet.ServletRequest;
import com.ttx.pattern.example.chain.tomcat.servlet.ServletResponse;

/**
 * 改过滤器将会替换request内容中的"B"字母,
 * 替换内容可以使用filterConfig配置, key为"replaceStr"
 *
 * @author TimFruit
 * @date 19-5-12 上午10:15
 */
public class ReplaceBFilter implements Filter {

    public static final String REPLACE_STR="replaceStr";
    private String replaceStr;

    @Override
    public void init(FilterConfig filterConfig) {
        String replaceStr1=filterConfig.getInitParameter(REPLACE_STR);
        if(replaceStr1==null){
            this.replaceStr="";
        }
        this.replaceStr=replaceStr1;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
        String responseStr=response.getResponse();

        if(responseStr==null){
            String requestStr=request.getRequest();
            if(requestStr==null){
                requestStr="";
            }
            responseStr=requestStr;
        }

        // 选择"承担责任", 替换"B"
        responseStr=responseStr.replace("B", replaceStr);
        response.setResponse(responseStr);

        //[warning] 这里是继续调用链, 也可以选择不继续调用
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
